import Vue from 'vue'
import VueRouter from 'vue-router'
import storage from '@/utils/local';

//提示路由名称重复的问题+ vue-routr 3.0.7
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

//路由1：默认的
const routes = [
  {
    path:"/login",
    name:"login",
    component:()=>import(/*webpackChunkName:"login"*/"@/views/Login.vue")
  }
]

//路由2：动态路由，需要权限的
const asyncRoutes = [
   //后台开始，每个模块，单独指定二级路由
   {
    path: '/',//首页
    name: 'index',
    visible:true,//在菜单中显示
    component:()=>import(/*webpackChunkName:"layout"*/"@/views/Layout/Layout.vue"),
    redirect:"/home", //默认加载后台的总的首页
    // redirect:{
    //   name:"home"
    // },
    meta:{
      title:"首页",
      icon:"iconfont icon-icon_home"
    },
    children:[
      {
        path: '/home',
        name: 'home',
        component:()=>import(/*webpackChunkName:"home" */"@/views/Home.vue"),
        meta:{title:"首页"}
      }
    ]
  },
  //商品管理
  {
    path:"/goods",
    name:"goods",
    meta:{
      title:"商品管理",
      icon:"iconfont icon-shangpin"
    },
    component:()=>import(/*webpackChunkName:"layout" */"@/views/Layout/Layout.vue"),
    redirect:"/goods/goods-list",
    visible:true,//在菜单中显示
    children:[
      {
        path:"/goods/goods-list",
        name:"goods-list",
        component:()=>import(/*webpackChunkName:"goods-list" */"@/views/Goods/GoodsList.vue"),
        meta:{
          // meta这个属性，自定义路由的其他信息
          title:"商品列表"
        }
      },
      {
        path:"/goods/goods-add",
        name:"goods-add",
        component:()=>import(/*webpackChunkName:"goods-add" */"@/views/Goods/GoodsAdd.vue"),
        meta:{title:"商品添加"}
      },
      {
        path:"/goods/goods-cate",
        name:"goods-cate",
        component:()=>import(/*webpackChunkName:"goods-cate" */"@/views/Goods/GoodsCate.vue"),
        meta:{title:"商品分类"}
      },
    ]
  },
  //订单
  {
    path:"/order",
    name:"order",
    meta:{title:"订单管理",icon:"iconfont icon-orderedlist-selected"},
    visible:true,//在菜单中显示
    component:()=>import(/*webpackChunkName:"layout"*/"@/views/Layout/Layout.vue"),
    // meta:{title:"订单管理"},
    redirect:"/order-list",
    children:[
      {
        path:"/order-list",
        name:"order-list",
        component:()=>import(/*webpackChunkName:"order-list"*/"@/views/Order/OrderList.vue"),
        meta:{title:"订单管理"}
      }
    ]
  },
  //店铺
  {
    path:"/shop",
    name:"shop",
    visible:true,//在菜单中显示
    component:()=>import(/*webpackChunkName:"layout"*/"@/views/Layout/Layout.vue"),
    meta:{title:"商铺管理",icon:"iconfont icon-dianpu"},
    redirect:"/",//店铺管理，子路由加/,并跳转到这里
    children:[
      {
        path:"/",
        component:()=>import(/*webpackChunkName:"shop"*/"@/views/Shop/Shop.vue"),
      }
    ]
  },
  //账号
  {
    path:"/account",
    name:"account",
    visible:true,//在菜单中显示
    component:()=>import(/* webpackChunkName:"layout" */"@/views/Layout/Layout.vue"),
    meta:{title:"账号管理",icon:"iconfont icon-zhanghao"},
    children:[
      {
        path:"/account/account-list",
        name:"account-list",
        component:()=>import(/* webpackChunkName:"account-list" */"@/views/Account/AccountList.vue"),
        meta:{
          title:"账号列表",
          role:['super']
        }
      },
      {
        path:"/account/account-add",
        name:"account-add",
        component:()=>import(/* webpackChunkName:"account-add" */"@/views/Account/AccountAdd.vue"),
        meta:{
          title:"账号添加",
          role:['super']
        }
      },
      {
        path:"/account/pass-modify",
        name:"pass-modify",
        component:()=>import(/* webpackChunkName:"pass-modify" */"@/views/Account/PassModify.vue"),
        meta:{title:"修改密码"}
      },
      {
        path:"/account/personal",
        name:"personal",
        component:()=>import(/* webpackChunkName:"personal" */"@/views/Account/Personal.vue"),
        meta:{title:"个人中心"}
      }
    ]
  },
  //统计
  {
    path:"/total",
    name:"total",
    component:()=>import(/* webpackChunkName:"layout" */"@/views/Layout/Layout.vue"),
    meta:{
      title:"销售统计",
      role:['super'], //权限配置,超级管理员可以访问
      icon:"iconfont icon-tongji"
    },
    visible:true,//在菜单中显示
    children:[
      {
        path:"/total/goods-total",
        name:"goods-total",
        component:()=>import(/* webpackChunkName:"goods-total" */"@/views/Total/GoodsTotal.vue"),
        meta:{title:"商品统计"}
      },
      {
        path:"/total/order-total",
        name:"order-total",
        component:()=>import(/* webpackChunkName:"order-total" */"@/views/Total/OrderTotal.vue"),
        meta:{title:"订单统计"}
      }
    ]
  },
  {
    path:"/exportExcel", //导出excel
    name:"export",
    component:()=>import(/*webpackChunkName:"login"*/"@/views/Page404.vue"),
    visible:false //这个路由是否在菜单中显示
  },
  {
    path:"/page404",
    name:"Page404",
    component:()=>import(/*webpackChunkName:"login"*/"@/views/Page404.vue"),
    visible:false //这个路由是否在菜单中显示
  },
  {
    path:"*",
    redirect:'/page404',
    visible:false //这个路由是否在菜单中显示
  }
]

//创建路由实例
const router = new VueRouter({
  routes
})

// router.$addRoutes = (params) => {
//   router.matcher = new VueRouter().matcher
//   router.addRoutes(params)
// }



//定义一个方法，根据用户角色，计算出自己的路由（导航菜单）
export function createRoutes() {
  let role = storage.get("role"); // 取出本地存储的角色
  console.log("当前用户角色:",role)

   // 计算出有权限访问的路由
   let accessRoutes = calcRoutes(asyncRoutes, role);
   console.log("当前用户的路由数组",accessRoutes)

  // 动态添加路由 【把算出来的权限路由 动态挂载到 路由对象上】
  router.addRoutes(accessRoutes); // addRoutes是路由内置的方法 可以动态添加路由
  // router.$addRoutes(accessRoutes);

  //计算左侧菜单
  let menus = calcMenus(accessRoutes,role)
  console.log("生成的菜单:",menus)

  // 存入本地,在左侧菜单组件中显示
  storage.set("menus", menus);
}

createRoutes(); // 初始化调用，生成路由

/**
 * @description: 计算出当前角色有权限访问的路由
 * @param: asyncRoutes 当前所有动态路由(需要配置权限的路由)
 * @param: role  当前用户角色
 * @returns:  数组 当前可以访问的路由数组
 */
function calcRoutes(asyncRoutes, role) {
  // 根据角色-循环过滤
  let accessRoutes = asyncRoutes.filter((router) => {
    // console.log(router)
    // return hasPermission(router,role)
    if(hasPermission(router,role)){
      //如果有子路由，需要重新在计算一遍子路由的权限
      if (router.children && router.children.length>0) {
        router.children = calcRoutes(router.children, role); // 递归过滤,并重新设置当前路由的子路由
      }
      return true;
    }else{
      false;
    }
  });
  return accessRoutes;
}

/**
 * @description: 判断当前路由对象 是否有权限
 * @param1: router 当前路由对象
 * @param2: role 当前用户角色
 * @returns: true 有权限 false 没有权限
 */
function hasPermission(router, role) {
  // 如果路由中有meta 且 meta中有role 证明是配置了权限 需要做权限的
  if (router.meta && router.meta.role) {
    return router.meta.role.includes(role);
  } else {
    // 否则就是没有配 [没有配置的 默认都是有权限]
    return true;
  }
}

//计算菜单相关方法
/**
 * 计算菜单
 * 参数1： 当前有权限访问的路由
 * 参数2： 当前角色
 */
function calcMenus(accessRoutes, role) {
  // 过滤菜单
  let arr = accessRoutes.filter((router) => {
    // 如果要在左侧显示
    if (isVisible(router, role)) {
      return true; // 返回true
    } else {
      return false; // 否则 不在左侧显示 返回false
    }
  });
  return arr; // 最后返回的 就是过滤出来的菜单
}

/*
  判断在不在左侧显示
  参数1：当前路由对象
  参数2: 当前角色
*/
function isVisible(router, role) {
  //每个需要显示菜单的，都需要加visible
  if (router.visible) {
    return true;//显示
  } else {
    return false;//不显示
  }
}

//添加路由全局守卫
var token = storage.get("t_k") ? true :false;

router.beforeEach((to,from,next)=>{
  //已经登录，放行
  if(token){
    next();
  }else{
     //没有登录，需要到登录页面
    // console.log(to)
    if(to.path=="/login"){
        next()//通过
    }else{
        next({name:"login"}) //访问的是其他页面，重新到登录页面
    }
  }
})

export default router
